package com.yema.retrofittest

import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.caimuhao.rxpicker.RxPicker
import com.caimuhao.rxpicker.bean.ImageItem
import com.yema.retrofittest.Http.DownFileJava
import com.yema.retrofittest.Http.MultipartBuilder
import com.yema.retrofittest.Http.MultipartBuilder.Companion.getRequestBody
import com.yema.retrofittest.Http.RetrofitMamnager
import com.yema.retrofittest.dataclass.ServerInfoResponse
import com.yema.retrofittest.dataclass.UploadFileModel
import com.yema.retrofittest.image.GlideImageLoader
import kotlinx.android.synthetic.main.activity_main.*
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okhttp3.ResponseBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.io.File
import java.net.URLEncoder
import kotlin.concurrent.thread


class MainActivity : AppCompatActivity(), View.OnClickListener {
    override fun onClick(v: View?) {

        when (v!!.id) {
            R.id.tv_click -> {
                val api = RetrofitMamnager.getApi()
                api.get(3).enqueue(object : retrofit2.Callback<ServerInfoResponse> {
                    override fun onFailure(call: Call<ServerInfoResponse>, t: Throwable) {
                        Log.e("tag", "")
                    }

                    override fun onResponse(call: Call<ServerInfoResponse>, response: Response<ServerInfoResponse>) {
                        val body = response.body()
                        Log.e("tag", body.toString())
                        println(body.toString())
                    }
                })
            }

            R.id.tvUpload -> {

                var files = mutableListOf<File>()
//                上传多张图片和参数
                RxPicker.init(GlideImageLoader())
                RxPicker.of()
                    .single(false)
                    .start(this).subscribe { list ->
                        list.forEach {
                            files.add(File(it.path))
                        }
                        val generateUploadBody = getRequestBody("file", files) {
                            put("name", "张德礼")
                            put("age", "18")
                        }

                        val execute = RetrofitMamnager.getApi().uploadMoreFile(generateUploadBody).execute()

                    }

            }
            R.id.tvOneFileAnddata -> {

                var files = mutableListOf<File>()

//                单张图片上传和参数
                RxPicker.init(GlideImageLoader())
                RxPicker.of()
                    .single(true)
                    .start(this).subscribe { list ->
                        thread {
                            Log.e("tag", "${list.size}")
                            val file = File(list[0].path)

                            list.forEach {
                                files.add(File(it.path))
                            }
                            val requestBody = getRequestBody("file", files)
                            val response = RetrofitMamnager.getApi().oneFileUpload(requestBody).execute()
                            Log.e("tag", "")


                        }


                    }
            }
            R.id.tv_onlyone -> {
//                只有一张图片
                RxPicker.init(GlideImageLoader())
                RxPicker.of()
                    .single(true)
                    .start(this).subscribe { list ->
                        thread {
                            Log.e("tag", "${list.size}")
//                            uploadAndData(list)
//                            oneFileUpload

                            val file = File(list[0].path)

                            val body = RequestBody.create(MediaType.parse("multipart/form-data"), file)

                            val encode = URLEncoder.encode(file.name, "UTF-8")
                            val part = MultipartBody.Part.createFormData("file", encode, body)

                            //图文上传
                            val body1 = MultipartBody.Builder().apply {
                                addPart(part)
                            }.build()


                            val response = RetrofitMamnager.getApi().oneFileUpload(body1).execute()
                            Log.e("tag", "")


                        }
                    }


            }
            R.id.tvdown -> {

                downFile()

            }


            /**
            上传json和其它参数
            json  单独上传  其它参数作为单独数据上传
             */
            R.id.tv_uploadjson -> {

                var filebody: RequestBody? = null

                var files = mutableListOf<File>()

                RxPicker.init(GlideImageLoader())
                RxPicker.of()
                    .single(false)
                    .start(this).subscribe { list ->

                        list.forEach {
                            files.add(File(it.path))
                        }
                        filebody = getRequestBody("file", files)
                        var data = """ {
                              "dictCode": "1087919827924869120",
                              "dictLabel": "用户",
                              "dictValue": "1"
                            }"""

                        val jsonbody = RequestBody.create(MediaType.parse("application/json"), data)

                        thread {
                            RetrofitMamnager.getApi().uploadJson2(jsonbody).execute()
                        }
                    }
            }
        }
    }


    private var intance: MainActivity? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        intance = this

        tvUpload.setOnClickListener(this)
        tvOneFileAnddata.setOnClickListener(this)
        tv_onlyone.setOnClickListener(this)
        tvdown.setOnClickListener(this)
        tv_uploadjson.setOnClickListener(this)

    }


    private fun uploadAndData(list: List<ImageItem>) {
        var files = mutableListOf<File>()

        for (path in list) {
            var file = File(path.path)
            files.add(file)
        }

        var datas = mutableMapOf<String, String>()
        datas["em"] = "em"
        datas["token"] = "token"


        val map = MultipartBuilder.multipleImgAnddData3(files = files, mutableMap = datas)
        val call = RetrofitMamnager.getApi().uploadFileWithRequestBody3(map)
        RetrofitMamnager.getApi().uploadFileWithRequestBody3(map).unwrapCall {
            if (this == null) {
            } else {
            }
        } ?: null

        call.enqueue(object : Callback<UploadFileModel> {
            override fun onFailure(call: Call<UploadFileModel>, t: Throwable) {}
            override fun onResponse(call: Call<UploadFileModel>, response: Response<UploadFileModel>) {}
        })
    }


    @JvmOverloads
    private fun downFile() {
        var url = "http://cp-short-video-1258603426.cos.ap-shanghai.myqcloud.com/qrcode/1089037745180045312.png"
        val downFile = RetrofitMamnager.getApi().downloadFile(url)
        downFile.enqueue(object : Callback<ResponseBody> {
            override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
                Log.e("tag", "")
            }

            override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
                val writeResponseBodyToDisk = DownFileJava.writeResponseBodyToDisk2(url, "COS", response, null)
                Log.e("tag", "")
            }
        })
    }


}
